# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import json
import logging

from tornado.web import RequestHandler
from collections import defaultdict

from agent.controller import search_active_feature_handler, search_active_domain_handler

logger = logging.getLogger('common')

class RollbackHandler(RequestHandler):
    def post(self):
        request_data = json.loads(self.request.body)
        logger.debug("Rollback request data:{}".format(request_data))

        rollback_result = defaultdict(dict)
        for domain_name in request_data['domains']:
            rollback_result[domain_name]['param_result'] = defaultdict(dict)
            
            # Rollback all related feature
            for feature_handler in search_active_feature_handler(domain_name):
                try:
                    feature_handler.rollback()
                    
                except Exception as e:
                    logger.error("rollback '{}:{}' failed: {}".format(
                        domain_name, feature_handler.__feature__, e
                    ))
                    rollback_result[domain_name]['param_result'][feature_handler.__feature__] = {
                        "suc": False, "msg": "{}".format(e)}
                    
                else:
                    logger.info("rollback feature '{}:{}' success".format(domain_name, feature_handler.__feature__))
                    rollback_result[domain_name]['param_result'][feature_handler.__feature__] = {
                        "suc": True, "msg": ""}
                    
            # Rollback domain
            domain_handler = search_active_domain_handler(domain_name)
            
            if domain_handler is None:
                rollback_result[domain_name]['suc'] = True
                rollback_result[domain_name]['msg'] = ""
                continue
            
            try:
                domain_handler.rollback()

            except Exception as e:
                logger.error("rollback '{}' failed: {}".format(
                    domain_name, e
                ))
                rollback_result[domain_name]['suc'] = False
                rollback_result[domain_name]['msg'] = "{}".format(e)
                logger.error("rollback domain '{}' success".format(domain_name))
            
            else:
                rollback_result[domain_name]['suc'] = True
                rollback_result[domain_name]['msg'] = ""
                logger.info("rollback domain '{}' success".format(domain_name))
            
        logger.debug("Rollback response data:{}".format(rollback_result))
        self.write(json.dumps(rollback_result))
        self.finish()